﻿Imports System.Web.Configuration
Imports System.Data.SqlClient
Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page
    Private connectionString As String = WebConfigurationManager.ConnectionStrings("Database").ConnectionString

    Dim passCheck As Boolean = True

    Protected Sub registerButton_Click(sender As Object, e As EventArgs) Handles registerButton.Click
        checkPasswords(newPasswordTextBox.Text.ToString, confirmNewPasswordTextBox.Text.ToString)
        If passCheck = True Then
            registerButton.PostBackUrl = "~Default.aspx"
            registerUser(newUserNameTextBox.Text.ToString, newPasswordTextBox.Text.ToString)
        Else
            registerButton.PostBackUrl = "~Default.aspx"
            registerErrorLabel.Text = "Please make sure your passwords match."
            registerErrorLabel.Visible = True

        End If

    End Sub

    Protected Sub checkPasswords(ByVal password1 As String, ByVal password2 As String)
        If password1.Equals(password2) Then 'I know the naming convention isn't the best, but it this case it is necessary.
            passCheck = True
        ElseIf Not password1.Equals(password2) Then
            passCheck = False
        End If
    End Sub

    Protected Sub registerUser(ByVal username As String, ByVal password As String)
        Dim insertSQL As New StringBuilder

        insertSQL.Append("INSERT INTO userTable(UserName, password)")
        insertSQL.Append("VALUES (@UserName, @password)")

        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(insertSQL.ToString, myConnection)

        With myCommand.Parameters
            .AddWithValue("@UserName", username)
            .AddWithValue("@password", password)
        End With
        Dim successBoolean As Boolean = True
        Try
            myConnection.Open()
            successBoolean = myCommand.ExecuteNonQuery
            registerErrorLabel.Text = "Welcome new Wizard! </br>Now try logging in."
            registerErrorLabel.Visible = True
        Catch ex As Exception
            successBoolean = False
            registerErrorLabel.Text = "Error creating your new Account. </br>Please Try again."
            registerErrorLabel.Visible = True
        Finally
            myConnection.Close()
        End Try
    End Sub


    Protected Sub loginButton_Click(sender As Object, e As System.EventArgs) Handles loginButton.Click
        Dim username As String
        username = loginUsernameTextBox.Text.ToString
        Dim password As String
        password = loginPasswordTextBox.Text.ToString
        Dim checkUserSQL As New StringBuilder
        Dim loginCheck As Boolean = True

        checkUserSQL.Append("SELECT * FROM userTable WHERE UserName = '")
        checkUserSQL.Append(username & "' AND password = '" & password & "'")

        Dim myConnection As New SqlConnection(connectionString)
        Dim myCommand As New SqlCommand(checkUserSQL.ToString, myConnection)
        Try
            myConnection.Open()
            Dim reader As SqlDataReader
            reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
            'loginCheck = myCommand.ExecuteNonQuery
            Dim rowChecker = reader.HasRows

            If rowChecker Then
                usernameHiddenField.Value = username
                'getUserID(username)
                loginButton.PostBackUrl = "UserPage.aspx"
                loginErrorLabel.Text = "Yes its working" 'used for debugging
                loginErrorLabel.Visible = True
                If rememberCheckBox.Checked = True Then
                    Dim loginCookie As HttpCookie = Request.Cookies("getLogin")
                    If loginCookie Is Nothing Then
                        loginCookie = New HttpCookie("getLogin")
                    End If
                    loginCookie("getLogin") = loginUsernameTextBox.Text
                    loginCookie.Expires = DateAndTime.Now.AddDays(1)
                    Response.Cookies.Add(loginCookie)
                End If

            Else
                'Need to fix this so that login errors appear and postback needs to be fixed.
                loginErrorLabel.Text = "Error Logging in. Please try again."
                loginErrorLabel.Visible = True
                loginButton.PostBackUrl = "~Default.aspx"
            End If
        Catch ex As Exception
            loginErrorLabel.Text = ("Error logging in. Please Try again.</br>" & ex.Message & " Was the error.")
            loginErrorLabel.Visible = True
            loginButton.PostBackUrl = "~Default.aspx"
        Finally
            myConnection.Close()
        End Try

        'Attempting to keep user logged in till they log off
        ' use cookies to keep value oflogged in individual, and keeps data in cookied until logged off
        'will create cookie on this page, and will keep cookie until you log off on user page, which will delete the cookie
    End Sub

    'Protected Sub getUserID(ByVal username As String)
    '    Dim getIDSQL As New StringBuilder
    '    getIDSQL.Append("SELECT * FROM userTable WHERE UserName = '" & username & "'")

    '    Dim myConnection As New SqlConnection(connectionString)
    '    Dim myCommand As New SqlCommand(getIDSQL.ToString, myConnection)
    '    Dim myReader As SqlDataReader
    '    Try
    '        myConnection.Open()
    '        myReader = myCommand.ExecuteReader
    '        myReader.Read()
    '        userIDHiddenField.Value = myReader("User_Id")
    '    Catch ex As Exception
    '        'do something
    '    Finally
    '        myConnection.Close()
    '    End Try
    'End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim loginCookie As HttpCookie = Request.Cookies("getLogin")
            If loginCookie IsNot Nothing Then
                rememberCheckBox.Checked = False
                rememberCheckBox.Visible = False
                loginErrorLabel.Text = "For safety purposes, we can not display your password"
                Dim login As String = loginCookie.Value
                Dim getlogin As String = login.Substring(login.IndexOf("=") + 1)
                loginUsernameTextBox.Text = getlogin
                rememberCheckBox.Checked = True

                Dim oldCookie As HttpCookie = Request.Cookies("getLogin")
                oldCookie.Expires = DateAndTime.Now.AddDays(-1)
                Response.Cookies.Add(oldCookie)

            Else
                rememberCheckBox.Checked = True
                rememberCheckBox.Visible = True
            End If
        End If

    End Sub

End Class
